import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_layout/base/index.dart';

class ScrollPage extends StatefulWidget {
  const ScrollPage({Key? key}) : super(key: key);

  @override
  _ScrollPageState createState() => _ScrollPageState();
}

class _ScrollPageState extends State<ScrollPage> {
  int currentIndex = 0;
  PageController pageController = PageController();
  List<CachePage> listPage = [
    const CachePage(
      title: "1",
    ),
    const CachePage(
      title: "2",
    ),
    const CachePage(
      title: "3",
    ),
    const CachePage(
      title: "4",
    ),
    const CachePage(
      title: "5",
    ),
    const CachePage(
      title: "6",
    ),
  ];

  @override
  Widget build(BuildContext context) {
    int index = 1;
    List<BottomNavigationBarItem> listBottom = [];
    for (var _ in listPage) {
      listBottom.add(BottomNavigationBarItem(
        icon: const Icon(Icons.access_alarm_rounded),
        label: "$index",
      ));
      index++;
    }
    return Scaffold(
      appBar: AppBar(
        title: const Text('滚动效果'),
      ),
      body: PageView(
        physics: const PageScrollPhysics(),
        controller: pageController,
        children: listPage,
        onPageChanged: (value) {
          currentIndex = value;
          _changeItem(currentIndex);
        },
      ),
      bottomNavigationBar: BottomNavigationBar(
        onTap: (value) {
          setState(() {
            currentIndex = value;
            showToast("$currentIndex");
            pageController.jumpToPage(currentIndex);
          });
        },
        type: BottomNavigationBarType.fixed,
        currentIndex: currentIndex,
        // backgroundColor: Colors.yellow,
        items: listBottom,
      ),
    );
  }

  void _changeItem(int value) {
    // pageController.position =1;
    // pageController.page = currentIndex.toDouble();
    setState(() {
      currentIndex = value;
    });
  }
}

// int index = 0;

// itemBuilder：列表条目的构建者
// initialItemCount：列表初始化条目的个数
// scrollDirection：滚动的方向
// reverse：是否翻转
// controller：滚动控制器
// primary：是否当用户点击状态栏时，该视图会滚动到顶部，只适用于iOS，默认支持
// physics：控制用户滚动视图的交互
// AlwaysScrollableScrollPhysics：列表总是可滚动的
// PageScrollPhysics：一页一页的列表滑动，一般用于PageView控件用的滑动效果，滑动到末尾会有比较大的弹起
// ClampingScrollPhysics：滚动时没有回弹效果
// NeverScrollableScrollPhysics：就算内容超过列表范围也不会滑动
// BouncingScrollPhysics：不论什么平台都会有回弹效果
// FixedExtentScrollPhysics：仅滚动到子项而不存在任何偏移，必须与使用FixedExtentScrollController的可滚动对象一起使用
// shrinkWrap：是否根据子widget的总长度来设置ListView的长度
// padding：父控件的内边距

// FixedExtentScrollController can only be used with ListWheelScrollViews
class CachePage extends StatefulWidget {
  final String? title;
  const CachePage({Key? key, this.title}) : super(key: key);

  @override
  _CachePageState createState() => _CachePageState();
}

class _CachePageState extends State<CachePage> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context);
    if (kDebugMode) {
      print("------------ViewPage---");
    }
    if (widget.title == "4") {
      var list = <Widget>[];
      for (int i = 0; i < 24; i++) {
        list.add(Container(
          height: 85,
          alignment: Alignment.center,
          color: Colors.primaries[i % Colors.primaries.length],
          child: Text(
            '$i',
            style: const TextStyle(color: Colors.white, fontSize: 20),
          ),
        ));
        // list[i] = ;
      }
      // return ListWheelScrollView.useDelegate(
      //   controller: FixedExtentScrollController(),
      //   physics: FixedExtentScrollPhysics(),
      //   itemExtent: 150,
      //   childDelegate: ListWheelChildBuilderDelegate(
      //       builder: (context, index) {
      //         return Container(
      //           margin: EdgeInsets.symmetric(vertical: 10, horizontal: 30),
      //           color: Colors.primaries[index % 10],
      //           alignment: Alignment.center,
      //           child: Text('$index'),
      //         );
      //       },
      //       childCount: 100),
      // );
      // return IndexedStack(children: [],);
      return ListWheelScrollView(
        itemExtent: 150,
        children: list,
        controller: FixedExtentScrollController(),
        physics: const FixedExtentScrollPhysics(),
      );
    }

    return CustomScrollView(
      // primary: true,
      // shrinkWrap: ,//
      slivers: <Widget>[
        SliverAppBar(
          // collapsedHeight: 0,
          foregroundColor: Colors.transparent,
          // backgroundColor: Colors.transparent,
          shadowColor: Colors.transparent,
          toolbarHeight: 0,
          centerTitle: true,
          pinned: true,
          expandedHeight: 230.0,
          flexibleSpace: FlexibleSpaceBar(
            centerTitle: true,
            collapseMode: CollapseMode.none,

            // title: Text('复仇者联盟',style: TextStyle(color: Colors.white),),
            background: Image.network(
              'http://img.haote.com/upload/20180918/2018091815372344164.jpg',
              fit: BoxFit.fitHeight,
            ),
          ),
        ),
        SliverGrid.count(
          crossAxisCount: 4,
          children: List.generate(8, (index) {
            return Container(
              color: Colors.primaries[index % Colors.primaries.length],
              alignment: Alignment.center,
              child: Text(
                '$index',
                style: const TextStyle(color: Colors.white, fontSize: 20),
              ),
            );
          }).toList(),
        ),
        SliverList(
          delegate: SliverChildBuilderDelegate((content, index) {
            return Container(
              height: 85,
              alignment: Alignment.center,
              color: Colors.primaries[index % Colors.primaries.length],
              child: Text(
                '$index',
                style: const TextStyle(color: Colors.white, fontSize: 20),
              ),
            );
          }, childCount: 25),
        )
      ],
    
      controller: "4" == widget.title ? FixedExtentScrollController() : null,
      physics: _getPhysics(widget.title),
    );
  }

  _getPhysics(String? title) {
    if ("1" == title) {
      return const AlwaysScrollableScrollPhysics();
    }
    if ("2" == title) {
      return const NeverScrollableScrollPhysics();
    }
    if ("3" == title) {
      return const ClampingScrollPhysics();
    }
    if ("5" == title) {
      return const PageScrollPhysics();
    }
    return const BouncingScrollPhysics();
  }

  @override
  bool get wantKeepAlive => true;
}

class MyPageView extends StatefulWidget {
  const MyPageView({Key? key}) : super(key: key);

  @override
  State<MyPageView> createState() => _MyPageViewState();
}

class _MyPageViewState extends State<MyPageView> {
  List<String> items = <String>['1', '2', '3', '4', '5'];

  void _reverse() {
    setState(() {
      items = items.reversed.toList();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: PageView.custom(
          childrenDelegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return KeepAlive(
                  data: items[index],
                  key: ValueKey<String>(items[index]),
                );
              },
              childCount: items.length,
              findChildIndexCallback: (Key key) {
                final ValueKey<String> valueKey = key as ValueKey<String>;
                final String data = valueKey.value;
                return items.indexOf(data);
              }),
        ),
      ),
      bottomNavigationBar: BottomAppBar(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextButton(
              onPressed: () => _reverse(),
              child: const Text('Reverse items'),
            ),
          ],
        ),
      ),
    );
  }
}

class KeepAlive extends StatefulWidget {
  const KeepAlive({Key? key, required this.data}) : super(key: key);

  final String data;

  @override
  State<KeepAlive> createState() => _KeepAliveState();
}

class _KeepAliveState extends State<KeepAlive> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ListView(
      children: List.generate(
        50,
        (index) => Container(
          color: Colors.amber,
          width: MediaQuery.of(context).size.width,
          height: 100,
          child: Column(
            children: [
              SizedBox(
                height: 99,
                child: Align(
                    child: Text(
                  "標題：${widget.data}---$index",
                )),
              ),
              const Divider(
                height: 1,
                color: Colors.black,
              )
            ],
          ),
        ),
      ),
    );
  }
}
